package yaq.mini.weibo.leafwb.Controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import yaq.mini.weibo.leafwb.pojo.Article;
import yaq.mini.weibo.leafwb.pojo.Comment;
import yaq.mini.weibo.leafwb.pojo.User;
import yaq.mini.weibo.leafwb.service.ArticleService;
import yaq.mini.weibo.leafwb.service.CommentService;
import yaq.mini.weibo.leafwb.service.FavouriteCollectionService;
import yaq.mini.weibo.leafwb.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/article")
public class ArticleController {
    @Value("${upload.directory}")
    private String uploadRoot;
    @Resource
    private UserService userService;
    @Resource
    private ArticleService articleService;
    @Resource
    private FavouriteCollectionService favouriteCollectionService;
    @Resource
    private CommentService commentService;

    @RequestMapping("/share")
    public String shareArticle(String content, Part[] imgFile, String imgCount, String shareId, int authority, HttpServletRequest request) {
        if (!isLogin(request))
            return "autoJumpAround";
        if (imgFile == null)
            return "redirect:/in/home?leftNav=1";
        //得到图片的地址
        List<String> urls = new ArrayList<>();
        int count = Integer.valueOf(imgCount);
        for (int i = 0; i < imgFile.length; i++) {
            int result = count & 1;
            count = count >> 1;
            if (result == 0)
                continue;
            String orgname = imgFile[i].getSubmittedFileName();
            System.out.println(System.getProperty("user.dir") + "\\src\\resource\\static\\head");
            String path = System.getProperty("user.dir") + "\\src\\resource\\static\\head";
            File file = new File(path);
            System.out.println(path);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String filename = uploadRoot + "/" + randName(orgname);
            try {
                imgFile[i].write(filename);
                urls.add(filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Date releaseTime = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String articleId = UUID.randomUUID() + "";
        Article article = new Article(articleId, shareId, content, dateFormat.format(releaseTime), (long) 0, (long) 0, authority);
        boolean issuccess = articleService.insertArticleByShare(article, urls);
        return "redirect:/in/home?leftNav=1";
    }

    /**
     * 检查评论的内容
     *
     * @param content
     * @param request
     * @return
     */
    @RequestMapping("/checkContent")
    @ResponseBody
    public Map<String, Boolean> shareContentCheck(String content, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isLegal", articleService.isContentIllegal(content));
        return map;
    }

    @RequestMapping("/share/check")
    @ResponseBody
    public Map<String, Object> shareCheck(String content, String userId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin) {
            map.put("isLegal", articleService.isContentIllegal(content));
            map.put("isAllowShare", userService.isAllowShare(userId));
        }
        return map;
    }

    @RequestMapping("deleteShare")
    @ResponseBody
    public Map<String, Boolean> deleteArticle(String articleId, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.deleteArticleByAId(articleId));
        return map;
    }

    @RequestMapping("/praise")
    @ResponseBody
    public Map<String, Boolean> praiseMe(String userId, String articleId, String isLike, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.updateArticleByLike(userId, articleId, isLike));
        return map;
    }

    @RequestMapping("/collect")
    @ResponseBody
    public Map<String, Boolean> collectArticle(String userId, String articleId, String isCollect, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.updateArticleByCollect(userId, articleId, isCollect));
        return map;
    }

    @RequestMapping("/shield")
    @ResponseBody
    public Map<String, Boolean> shieldArticle(String userId, String articleId, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", favouriteCollectionService.updateByShield(articleId, userId, "T"));
        return map;
    }

    @RequestMapping("/comment")
    @ResponseBody
    public Map<String, Object> commentShare(String content, String userId, String articleId) {
        String commentId = UUID.randomUUID() + "";
        Date commentTime = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Comment comment = new Comment(commentId, articleId, userId, dateFormat.format(commentTime), content);
        Boolean isSuccess = commentService.insertByComment(comment);
        isSuccess = isSuccess && articleService.updateArticleByComment(articleId, 1);
        Map<String, Object> map = new HashMap<>();
        map.put("commentId", commentId);
        map.put("isSuccess", isSuccess);
        return map;
    }

    @RequestMapping("deleteComment")
    @ResponseBody
    public Map<String, Boolean> deleteComment(String commentId, HttpServletRequest request) {
        System.out.println(commentId);
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", commentService.deleteComment(commentId));
        return map;
    }

    @RequestMapping("updateHead")
    public String updateHeadImage(Part img, String userId, HttpServletRequest request) {
        if (!isLogin(request))
            return "autoJumpAround";
        if (img != null) {
            String orgname = img.getSubmittedFileName();
            String filename = uploadRoot + "/head/" + randName(orgname);
            try {
                String oldUrl = userService.getHeadUrl(userId);
                System.out.println(oldUrl);
                if (!oldUrl.contains("/head/initHeadPic.png")) {
                    File oldImg = new File(oldUrl);
                    oldImg.delete();
                }
                img.write(filename);
                userService.updateHeadUrl(userId, filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "redirect:/in/home?leftNav=5";
    }

    @RequestMapping("updateUserMsg")
    @ResponseBody
    public Map<String, Boolean> updateUserMessage(String userId, String nickname, String address, String sex, String birthday, String introduction, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", userService.updateUserMessage(userId, nickname, address, sex, birthday == "" ? null : birthday, introduction));
        return map;
    }

    @RequestMapping("/updatePsw")
    @ResponseBody
    public Map<String, Boolean> updatePassword(String oldPsw, String newPassword, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin) {
            String userId = MainController.getValueByCookieName("userId", request);
            boolean isPswOK = userService.isUserExit(userId, oldPsw);
            boolean isSuccess = isPswOK && userService.updatePassword(userId, newPassword);
            map.put("isPswOK", isPswOK);
            map.put("isSuccess", isSuccess);
        }
        return map;
    }

    @RequestMapping("/updateAuthority")
    @ResponseBody
    public Map<String, Boolean> updateShareAuthority(String articleId, int authority, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.updateArticleByAuthority(articleId, authority));
        return map;
    }

    @RequestMapping("updateAllowShare")
    @ResponseBody
    public Map<String, Boolean> updateAllowShare(String userId, String isAllowShare, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", userService.updateAllowShare(userId, isAllowShare));
        return map;
    }

    @RequestMapping("updateKeyword")
    @ResponseBody
    public Map<String, Boolean> updateKeyword(String keyword, String newKeyword, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.updateKeyword(keyword, newKeyword));
        return map;
    }

    @RequestMapping("deleteKeyword")
    @ResponseBody
    public Map<String, Boolean> deleteKeyword(String keyword, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.deleteKeyword(keyword));
        return map;
    }

    @RequestMapping("addKeyword")
    @ResponseBody
    public Map<String, Boolean> addKeyword(String keyword, HttpServletRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        boolean isLogin = isLogin(request);
        map.put("isLogin", isLogin(request));
        if (isLogin)
            map.put("isSuccess", articleService.addKeyword(keyword));
        return map;
    }

    @RequestMapping("searchShare")
    public ModelAndView searchArticle(String key, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<Article> articleList = articleService.listArticlesByKey(key);
        map.put("searchArticleList", articleList);
        map.put("isLogin", isLogin(request));
        if (isLogin(request)) {
            String userId = MainController.getValueByCookieName("userId", request);
            List<String> likerList = favouriteCollectionService.listArticleIdByLike(userId);
            List<String> collectorList = favouriteCollectionService.listArticleIdByCollect(userId);
            User user = userService.getUserByLogin(userId);
            map.put("user", user);
            map.put("likerList", likerList);
            map.put("collectorList", collectorList);
        }
        map.put("isSearch", true);
        map.put("key", key);
        ModelAndView mv = new ModelAndView("/in/articleDetail", map);
        return mv;
    }

    @RequestMapping("share_detail")
    public ModelAndView turnToArticle(@RequestParam(name = "aId") String articleId, HttpServletRequest request) {
        Article article = articleService.getArticleByID(articleId);
        Map<String, Object> map = new HashMap<>();
        map.put("article", article);
        String userId = MainController.getValueByCookieName("userId", request);
        if (userId.length() > 0) {
            map.put("isLogin", true);
            User user = userService.getUserByLogin(userId);
            map.put("user", user);
            articleService.listArticlesByUserID(userId);
            List<String> likerList = favouriteCollectionService.listArticleIdByLike(userId);
            List<String> collectorList = favouriteCollectionService.listArticleIdByCollect(userId);
            map.put("likerList", likerList);
            map.put("collectorList", collectorList);
        } else {
            map.put("isLogin", false);
        }
        List<String> userIds = favouriteCollectionService.listUserIdByLike(articleId);
        if (userIds.contains(userId)) {
            int index = userIds.indexOf(userId);
            userIds.set(index, userIds.get(0));
            userIds.set(0, userId);
        }
        List<User> likers = userService.getUserByIDs(userIds);
        map.put("likers", likers);
        ModelAndView mv = new ModelAndView("/in/articleDetail", map);
        return mv;
    }

    //生成随机唯一名称
    private String randName(String oldname) {
        return UUID.randomUUID() + oldname.substring(oldname.lastIndexOf('.'));
    }

    /**
     * 判断是否登录
     *
     * @param request
     * @return
     */
    private boolean isLogin(HttpServletRequest request) {
        String userId = MainController.getValueByCookieName("userId", request);
        boolean isLogin = true;
        if (userId.length() == 0)
            isLogin = false;
        return isLogin;
    }
}
